package com.lizemin.beanfactorypostprocessor.processors;

import com.lizemin.beanfactorypostprocessor.entity.Cat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * @author lzm
 * @date 2025/9/27 13:24
 * @description
 */
@Slf4j
@Component
public class AddOrRemoveBeanDefinitionPostProcessor implements BeanDefinitionRegistryPostProcessor, EnvironmentAware {

    private Environment environment;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        log.info("开始添加cat的beanDefinition");
        GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
        genericBeanDefinition.setBeanClass(Cat.class);

        MutablePropertyValues catPropertyValues = new MutablePropertyValues();
        catPropertyValues.addPropertyValue("name", "黑猫警长");
        catPropertyValues.addPropertyValue("color", "白色");
        genericBeanDefinition.setPropertyValues(catPropertyValues);

        registry.registerBeanDefinition("cat", genericBeanDefinition);

        boolean removeFlag = environment.getProperty("removePhone", boolean.class, false);
        if (removeFlag) {
            log.info("下面开始移除phone的beanDefinition");
            registry.removeBeanDefinition("phone");
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        BeanDefinition beanDefinition = beanFactory.getBeanDefinition("cat");
        log.info("开始打印cat的属性值");
        for (PropertyValue propertyValue : beanDefinition.getPropertyValues().getPropertyValues()) {
            log.info("{} => {}", propertyValue.getName(), propertyValue.getValue());
        }
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
